import React from "react";

import { useSelector } from "react-redux";
import { Link } from "react-router-dom";
import { selectAuthorById } from "./authorsSlice";
import { selectPostsByAuthor } from "./postsSlices";

export const AuthorPage = ({ match }) => {
  const { authorId } = match.params

  const author = useSelector(state => selectAuthorById(state, authorId))

  //const postsForAuthor = useSelector(state => {
  //  const allPosts = selectAllPost(state)
  //  return allPosts.filter(post => post.user === authorId)
  //})
  const postsForAuthor = useSelector(state => selectPostsByAuthor(state, authorId))

  const postTitles = postsForAuthor.map(post => (
    <li key={post.id}>
      <Link to={`/posts/${post.id}`}>{post.title}</Link>
    </li>
  ))

  return (
    <section>
      <h2>{author.name}</h2>
      <ul>{postTitles}</ul>
    </section>
  )
}